package com.company.jrlz.service.http;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.company.jrlz.service.http.HttpUrlService;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

@Service(HttpUrlService.NAME)
public class HttpUrlServiceBean implements HttpUrlService {

    private static final Logger LOGGER = LoggerFactory.getLogger(HttpUrlServiceBean.class);

    @Override
    public String sendGet(String urlParam, Map<String, String> parameters) {
        String result = "";
        HttpURLConnection httpURLConnection = null;
        InputStream inputStream = null;
        BufferedReader bufferedReader = null;
        StringBuffer resultBuffer = null;
        // http://10.13.200.126:7788
        String urlS = "http://localhost:7788"+urlParam;
        StringBuffer sb = new StringBuffer();
        String params = "";
        try{
            if(parameters!=null){
                if(parameters.size()==1){
                    for(String name:parameters.keySet()){
                        sb.append(name).append("=").append(
                                URLEncoder.encode(parameters.get(name),"UTF-8")
                        );
                    }
                    params = sb.toString();
                }else {
                    for (String name:parameters.keySet()){
                        sb.append(name).append("=").append(
                                URLEncoder.encode(parameters.get("name"),"UTF-8")
                        ).append("&");
                    }
                    String temp_params = sb.toString();
                    params = temp_params.substring(0,temp_params.length()-1);
                }
            }
            String full_url = urlS + "?" +params;

            URL url = new URL(full_url);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.setRequestProperty("Content-Type", "application/json");
            httpURLConnection.setRequestProperty("Accept", "application/json");
            httpURLConnection.setRequestProperty("Accept-Charset", "UTF-8");
            // 允许写出
            httpURLConnection.setDoOutput(true);
            // 超时时间：3s
            httpURLConnection.setConnectTimeout(3000);
            if(httpURLConnection.getResponseCode() != HttpURLConnection.HTTP_OK){
                result = httpURLConnection.getResponseCode()+"";
            }else if(httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK){
                inputStream = httpURLConnection.getInputStream();
                resultBuffer = new StringBuffer();
                String line ;
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
                while((line = bufferedReader.readLine())!=null){
                    resultBuffer.append(line);
                }
                result = resultBuffer.toString();
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(inputStream !=null){
                try{
                    inputStream.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
            httpURLConnection.disconnect();
        }
        LOGGER.info("GET请求获取的数据为:" + result);
        return result;
    }

    @Override
    public String sendPost(String urlParam, String data) {
        String result = "";
        HttpURLConnection httpURLConnection = null;
        InputStream inputStream = null;
        OutputStreamWriter outputStreamWriter = null;
        BufferedReader bufferedReader = null;
        StringBuffer resultBuffer = null;
        // http://10.13.200.126:7788
        String urlS = "http://localhost:7788"+urlParam;
        try{
            URL url = new URL(urlS);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setRequestProperty("Content-Type", "application/json");
            httpURLConnection.setRequestProperty("Accept", "application/json");
            httpURLConnection.setDoOutput(true);
            outputStreamWriter = new OutputStreamWriter(httpURLConnection.getOutputStream());
            outputStreamWriter.write(data);
            outputStreamWriter.flush();
            outputStreamWriter.close();
            if(httpURLConnection.getResponseCode() != HttpURLConnection.HTTP_OK){
                throw  new RuntimeException("HTTP POST Request Failed with Error code : "
                        +httpURLConnection.getResponseCode());
            }
            inputStream = httpURLConnection.getInputStream();
            resultBuffer = new StringBuffer();
            String line;
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
            while((line = bufferedReader.readLine())!= null){
                resultBuffer.append(line);
            }
            result = resultBuffer.toString();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(inputStream != null){
            try{
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            httpURLConnection.disconnect();
        }
        LOGGER.info("POST请求获取数据为："+result);
        return result;
    }

}